<!DOCTYPE html>
<html lang="zh-CN">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0, maximum-scale=1.0, user-scalable=no">
    <title>星格 - 星座每日小挑战</title>
    <script src="https://cdn.tailwindcss.com"></script>
    <link href="https://cdn.jsdelivr.net/npm/font-awesome@4.7.0/css/font-awesome.min.css" rel="stylesheet">
    <script>
        tailwind.config = {
            theme: {
                extend: {
                    colors: {
                        primary: '#6C5CE7',
                        secondary: '#FD79A8',
                        accent: '#00B894',
                        dark: '#2D3436',
                        light: '#F8F9FA'
                    },
                    fontFamily: {
                        sans: ['Inter', 'system-ui', 'sans-serif'],
                    },
                }
            }
        }
    </script>
    <style>
        .mask-blur { backdrop-filter: blur(6px); }
        @keyframes popIn { 0% { transform: scale(0.9); opacity: 0 } 100% { transform: scale(1); opacity: 1 } }
        
        .ribbon {
            position: absolute; top: 10px; left: -8px; color: #fff; font-size: 12px; font-weight: 700;
            background: linear-gradient(135deg, #f59e0b, #f97316);
            padding: 6px 12px; border-top-right-radius: 8px; border-bottom-right-radius: 8px;
            box-shadow: 0 6px 14px rgba(249, 115, 22, 0.3);
        }
        .ribbon::after {
            content: '';
            position: absolute; right: -8px; top: 0; width: 0; height: 0;
            border-top: 8px solid #c2410c; border-left: 8px solid transparent;
        }
    </style>
    <meta name="description" content="每天 1 个与星座相关的小挑战，低门槛、即时反馈，提升完成感和活力。">
</head>
<body class="min-h-screen bg-gradient-to-br from-purple-50 via-rose-50 to-amber-50">
    <div class="container mx-auto px-4 py-5">
        <header class="flex items-center justify-between mb-5">
            <button onclick="history.back()" class="w-9 h-9 rounded-full bg-white border border-gray-200 flex items-center justify-center text-gray-600 hover:bg-gray-50"><i class="fa fa-angle-left"></i></button>
            <h1 class="text-lg font-bold text-gray-800">星座每日小挑战</h1>
            <button id="open-preview-modal" class="w-9 h-9 rounded-full bg-white border border-gray-200 flex items-center justify-center text-yellow-600 hover:bg-yellow-50" title="预览完成弹框">
                <i class="fa fa-trophy"></i>
            </button>
        </header>

        <section class="bg-white/80 mask-blur border border-purple-100 rounded-2xl shadow p-5 relative overflow-hidden">
            <div class="absolute -right-10 -top-10 w-40 h-40 bg-gradient-to-br from-purple-100 to-pink-100 rounded-full"></div>
            <div class="relative z-10">
                <div class="flex items-center justify-between">
                    <div class="flex items-center gap-3">
                        <div class="w-12 h-12 rounded-full overflow-hidden border border-purple-100 bg-white flex items-center justify-center">
                            <img id="zodiac-avatar" src="assets/zodiac/aries.svg" alt="白羊座" class="w-10 h-10">
                        </div>
                        <div>
                            <div class="text-sm text-gray-500" id="challenge-date"></div>
                            <div class="text-base font-semibold text-gray-800"><span id="zodiac-name">白羊座</span> · 今日小挑战</div>
                        </div>
                    </div>
                    <div>
                        <select id="zodiac-select" class="text-sm border rounded-lg px-3 py-2 bg-white">
                            <option value="aries">白羊座</option>
                            <option value="taurus">金牛座</option>
                            <option value="gemini">双子座</option>
                            <option value="cancer">巨蟹座</option>
                            <option value="leo">狮子座</option>
                            <option value="virgo">处女座</option>
                            <option value="libra">天秤座</option>
                            <option value="scorpio">天蝎座</option>
                            <option value="sagittarius">射手座</option>
                            <option value="capricorn">摩羯座</option>
                            <option value="aquarius">水瓶座</option>
                            <option value="pisces">双鱼座</option>
                        </select>
                    </div>
                </div>

                <div class="mt-4 p-4 bg-gradient-to-br from-white to-purple-50 rounded-xl border border-purple-100">
                    <h3 class="text-sm font-medium text-gray-700 mb-2 flex items-center"><i class="fa fa-flag text-primary mr-2"></i>今日挑战</h3>
                    <p id="challenge-text" class="text-gray-800 text-sm leading-relaxed"></p>
                </div>

                <div class="mt-4 flex items-center gap-3">
                    <button id="btn-complete" class="px-4 py-2 rounded-xl bg-gradient-to-r from-primary to-secondary text-white text-sm shadow hover:opacity-95">
                        <i class="fa fa-check mr-1"></i>已完成
                    </button>
                    <button id="btn-share" class="px-4 py-2 rounded-xl border text-sm text-gray-700 border-gray-200 bg-white hover:bg-gray-50">
                        <i class="fa fa-share-alt mr-1"></i>分享成就
                    </button>
                    <span id="complete-badge" class="hidden text-xs px-2 py-1 rounded-full bg-emerald-50 text-emerald-700 border border-emerald-200">今日已完成</span>
                </div>
            </div>
        </section>

        <div class="text-center text-xs text-gray-500 mt-5">每日更新 · 低门槛 · 即时反馈</div>

        <!-- 最近一周完成统计与列表 -->
        <section class="mt-5 grid grid-cols-1 gap-4">
            <div class="bg-white/80 mask-blur border border-emerald-100 rounded-2xl shadow p-5">
                <h3 class="text-sm font-semibold text-gray-800 mb-3 flex items-center"><i class="fa fa-line-chart text-emerald-600 mr-2"></i>最近 7 天完成统计</h3>
                <div class="flex items-center justify-between">
                    <div class="text-sm text-gray-700">完成次数：<span id="week-done-count" class="font-semibold text-emerald-700">0</span> / 7</div>
                    <div id="week-dots" class="flex items-center gap-1"></div>
                </div>
            </div>
            <div class="bg-white/80 mask-blur border border-purple-100 rounded-2xl shadow p-5">
                <h3 class="text-sm font-semibold text-gray-800 mb-3 flex items-center"><i class="fa fa-list-ul text-purple-600 mr-2"></i>最近完成列表（最多 7 条）</h3>
                <ul id="recent-list" class="space-y-2"></ul>
            </div>
        </section>
    </div>

    <!-- 反馈弹框（居中小弹窗） -->
    <div id="feedback-modal" class="fixed inset-0 bg-black/40 hidden">
        <div id="feedback-panel" class="absolute left-1/2 top-1/2 -translate-x-1/2 -translate-y-1/2 w-[92%] max-w-sm rounded-2xl overflow-hidden bg-white shadow-2xl opacity-0 scale-95 transition duration-200">
            <div class="relative bg-gradient-to-br from-emerald-400 via-emerald-500 to-emerald-600 text-white">
                <div class="absolute -top-10 -right-10 w-40 h-40 bg-white/10 rounded-full"></div>
                <div class="p-5 flex items-start gap-3">
                    <div class="w-11 h-11 rounded-xl bg-white/20 flex items-center justify-center shadow"><i class="fa fa-trophy"></i></div>
                    <div class="flex-1">
                        <h4 id="feedback-title" class="font-bold text-base mb-1">恭喜完成！</h4>
                        <p id="feedback-text" class="text-sm text-white/90"></p>
                    </div>
                    <button id="close-feedback" class="w-8 h-8 rounded-full bg-white/15 border border-white/25 flex items-center justify-center"><i class="fa fa-times text-white"></i></button>
                </div>
            </div>
            <div class="p-4 flex items-center justify-end gap-3">
                <button id="share-feedback" class="px-4 py-2 rounded-xl bg-gradient-to-r from-purple-500 to-pink-500 text-white text-sm shadow"><i class="fa fa-share-alt mr-1"></i>晒一晒</button>
                <button id="ok-feedback" class="px-4 py-2 rounded-xl border text-sm text-gray-700 border-gray-200 bg-white hover:bg-gray-50">好的</button>
            </div>
        </div>
    </div>

    <script>
        const zodiacMap = {
            aries: { name: '白羊座', img: 'assets/zodiac/aries.svg' },
            taurus: { name: '金牛座', img: 'assets/zodiac/taurus.svg' },
            gemini: { name: '双子座', img: 'assets/zodiac/gemini.svg' },
            cancer: { name: '巨蟹座', img: 'assets/zodiac/cancer.svg' },
            leo: { name: '狮子座', img: 'assets/zodiac/leo.svg' },
            virgo: { name: '处女座', img: 'assets/zodiac/virgo.svg' },
            libra: { name: '天秤座', img: 'assets/zodiac/libra.svg' },
            scorpio: { name: '天蝎座', img: 'assets/zodiac/scorpio.svg' },
            sagittarius: { name: '射手座', img: 'assets/zodiac/sagittarius.svg' },
            capricorn: { name: '摩羯座', img: 'assets/zodiac/capricorn.svg' },
            aquarius: { name: '水瓶座', img: 'assets/zodiac/aquarius.svg' },
            pisces: { name: '双鱼座', img: 'assets/zodiac/pisces.svg' },
        };

        // 每日挑战与反馈文案
        const dailyChallenge = {
            aries: {
                text: '今天主动和 1 位陌生同事打招呼，展示你的热情与活力。',
                feedback: '恭喜你！今天的互动让你收获了同事的好感，白羊的社交魅力满分～'
            },
            taurus: {
                text: '今天尝试更健康的一餐，稳中求进，从饮食开始。',
                feedback: '太赞了！一步一个脚印，金牛的稳定让改变更持久～'
            },
            gemini: {
                text: '今天与 1 位朋友深入聊 10 分钟，分享一个新想法。',
                feedback: '思维的火花点亮交流，双子的人际魅力持续在线～'
            },
            cancer: {
                text: '今天给家人或朋友发一句关心的话。',
                feedback: '温柔是你的超能力，巨蟹的贴心让关系更近一步～'
            },
            leo: {
                text: '今天在会议中主动发言 1 次，展示你的自信。',
                feedback: '舞台属于你！狮子的表达让大家看到你的光芒～'
            },
            virgo: {
                text: '今天整理一个小区域（桌面/文件夹），提升条理感。',
                feedback: '秩序感就是生产力，处女的细致让效率加分～'
            },
            libra: {
                text: '纠结“吃火锅还是日料”？10 分钟内做出决定。',
                feedback: '你今天的果断超棒！天秤偶尔的快速决策让生活更高效～'
            },
            scorpio: {
                text: '今天花 15 分钟专注于一件需要深入的事情。',
                feedback: '专注产生洞察，天蝎的深度让成果更扎实～'
            },
            sagittarius: {
                text: '今天下班后步行/骑行 10 分钟，给心灵放个风。',
                feedback: '自由带来好心情，射手的小小探索也很治愈～'
            },
            capricorn: {
                text: '今天写下 1 个本周关键目标，并推进 1 步。',
                feedback: '稳步推进最踏实，摩羯的执行力让目标更近～'
            },
            aquarius: {
                text: '今天尝试一个小小的新方法/新工具。',
                feedback: '灵感+行动=惊喜，水瓶的创意让日常更有趣～'
            },
            pisces: {
                text: '今天记录 3 件让你感到温暖的小事。',
                feedback: '温柔与想象力是你的光，双鱼的感受力很动人～'
            },
        };

        const el = {
            date: document.getElementById('challenge-date'),
            avatar: document.getElementById('zodiac-avatar'),
            name: document.getElementById('zodiac-name'),
            select: document.getElementById('zodiac-select'),
            text: document.getElementById('challenge-text'),
            complete: document.getElementById('btn-complete'),
            share: document.getElementById('btn-share'),
            badge: document.getElementById('complete-badge'),
            modal: document.getElementById('feedback-modal'),
            modalPanel: null,
            modalTitle: document.getElementById('feedback-title'),
            modalText: document.getElementById('feedback-text'),
            modalClose: document.getElementById('close-feedback'),
        };

        function getTodayKey() {
            const d = new Date();
            const yyyy = d.getFullYear();
            const mm = String(d.getMonth() + 1).padStart(2, '0');
            const dd = String(d.getDate()).padStart(2, '0');
            return `${yyyy}-${mm}-${dd}`;
        }

        function getStorageKey(zodiac) {
            return `dailyChallenge:${zodiac}:${getTodayKey()}`;
        }

        function getLogKey(zodiac) {
            return `dailyChallenge:log:${zodiac}`;
        }

        function getLastNDates(n) {
            const res = [];
            const d = new Date();
            for (let i = 0; i < n; i++) {
                const x = new Date(d);
                x.setDate(d.getDate() - i);
                const yyyy = x.getFullYear();
                const mm = String(x.getMonth() + 1).padStart(2, '0');
                const dd = String(x.getDate()).padStart(2, '0');
                res.push(`${yyyy}-${mm}-${dd}`);
            }
            return res;
        }

        function readLog(zodiac) {
            try {
                const raw = localStorage.getItem(getLogKey(zodiac));
                if (!raw) return [];
                const arr = JSON.parse(raw);
                if (!Array.isArray(arr)) return [];
                // 兼容旧数据：字符串表示的日期，转为对象
                return arr.map(item => {
                    if (typeof item === 'string') return { date: item, text: (dailyChallenge[zodiac] || dailyChallenge.aries).text };
                    if (item && typeof item === 'object' && item.date) return item;
                    return null;
                }).filter(Boolean);
            } catch { return []; }
        }

        function writeLog(zodiac, entries) {
            try { localStorage.setItem(getLogKey(zodiac), JSON.stringify(entries)); } catch {}
        }

        function addToLogToday(zodiac) {
            const today = getTodayKey();
            const list = readLog(zodiac);
            const exists = list.find(e => e.date === today);
            if (!exists) list.unshift({ date: today, text: (dailyChallenge[zodiac] || dailyChallenge.aries).text });
            // 只保留最近 30 条以免过大
            writeLog(zodiac, list.slice(0, 30));
        }

        function renderWeeklyStats(zodiac) {
            const last7 = getLastNDates(7);
            const doneFlags = last7.map(date => localStorage.getItem(`dailyChallenge:${zodiac}:${date}`) === '1');
            const doneCount = doneFlags.filter(Boolean).length;

            const countEl = document.getElementById('week-done-count');
            if (countEl) countEl.textContent = String(doneCount);

            const dots = document.getElementById('week-dots');
            if (dots) {
                dots.innerHTML = '';
                // 显示从最早到今天的顺序
                for (let i = last7.length - 1; i >= 0; i--) {
                    const done = doneFlags[i];
                    const el = document.createElement('div');
                    el.title = last7[i];
                    el.className = `w-6 h-6 rounded-lg border text-[10px] flex items-center justify-center ${done ? 'bg-emerald-500 border-emerald-600 text-white' : 'bg-gray-100 border-gray-200 text-gray-400'}`;
                    el.textContent = new Date(last7[i]).getDate();
                    dots.appendChild(el);
                }
            }

            // 列表：优先使用日志，其次用最近 7 天内完成的日期
            const listEl = document.getElementById('recent-list');
            if (listEl) {
                const log = readLog(zodiac);
                const fallbackDates = last7.filter((d, idx) => doneFlags[idx]);
                const fallback = fallbackDates.map(d => ({ date: d, text: (dailyChallenge[zodiac] || dailyChallenge.aries).text }));
                const items = (log.length ? log : fallback).slice(0, 7);
                if (items.length === 0) {
                    listEl.innerHTML = '<li class="text-xs text-gray-500">暂未有完成记录，快去完成今日挑战吧～</li>';
                } else {
                    listEl.innerHTML = items.map(entry => {
                        const dateStr = entry.date;
                        const weekday = ['日','一','二','三','四','五','六'][new Date(dateStr).getDay()];
                        const text = entry.text || (dailyChallenge[zodiac] || dailyChallenge.aries).text;
                        return `<li class="p-3 rounded-lg border border-gray-100 bg-white">
                            <div class="flex items-center justify-between">
                                <span class="text-sm font-medium text-gray-800">${dateStr}（周${weekday}）</span>
                                <span class="text-[11px] px-2 py-1 rounded-full bg-emerald-50 text-emerald-700 border border-emerald-200">已完成</span>
                            </div>
                            <div class="text-xs text-gray-600 mt-1 line-clamp-2">${text}</div>
                        </li>`;
                    }).join('');
                }
            }
        }

        function render(zodiac) {
            const meta = zodiacMap[zodiac] || zodiacMap.aries;
            const content = dailyChallenge[zodiac] || dailyChallenge.aries;
            if (el.date) el.date.textContent = getTodayKey();
            if (el.avatar) el.avatar.src = meta.img;
            if (el.name) el.name.textContent = meta.name;
            if (el.text) el.text.textContent = content.text;

            // 状态
            const completed = localStorage.getItem(getStorageKey(zodiac)) === '1';
            if (completed) {
                el.badge.classList.remove('hidden');
                el.complete.disabled = true;
                el.complete.classList.add('opacity-70');
                el.complete.innerHTML = '<i class="fa fa-check mr-1"></i>今天已完成';
            } else {
                el.badge.classList.add('hidden');
                el.complete.disabled = false;
                el.complete.classList.remove('opacity-70');
                el.complete.innerHTML = '<i class="fa fa-check mr-1"></i>已完成';
            }
        }

        function openModal(text) {
            const modal = el.modal;
            const panel = document.getElementById('feedback-panel');
            if (!modal || !panel) return;
            el.modalText.textContent = text;
            modal.classList.remove('hidden');
            requestAnimationFrame(() => { panel.style.opacity = '1'; panel.style.transform = 'translate(-50%, -50%) scale(1)'; });
            // 彩带动画
            const layer = document.getElementById('confetti-layer');
            if (layer) {
                layer.innerHTML = '';
                const colors = ['#fff176','#ff8a65','#4dd0e1','#81c784','#ba68c8','#ffd54f'];
                for (let i = 0; i < 36; i++) {
                    const c = document.createElement('div');
                    const size = 6 + Math.round(Math.random() * 6);
                    c.className = 'confetti';
                    c.style.left = Math.round(Math.random() * 100) + '%';
                    c.style.top = (-10 - Math.random() * 20) + 'px';
                    c.style.background = colors[Math.floor(Math.random() * colors.length)];
                    c.style.width = size + 'px';
                    c.style.height = (size + 4) + 'px';
                    c.style.animationDelay = (Math.random() * 0.4) + 's';
                    layer.appendChild(c);
                }
            }
        }
        function closeModal() {
            const modal = el.modal;
            const panel = document.getElementById('feedback-panel');
            if (!modal || !panel) return;
            panel.style.opacity = '0';
            panel.style.transform = 'translate(-50%, -50%) scale(0.95)';
            setTimeout(() => modal.classList.add('hidden'), 200);
        }

        // 初始化
        (function init() {
            // 从 URL 或本地选择读取星座
            const urlParams = new URLSearchParams(location.search);
            const paramZodiac = urlParams.get('zodiac');
            const defaultZodiac = localStorage.getItem('preferredZodiac') || 'aries';
            const zodiac = zodiacMap[paramZodiac] ? paramZodiac : defaultZodiac;
            el.select.value = zodiac;
            render(zodiac);

            el.select.addEventListener('change', () => {
                const z = el.select.value;
                localStorage.setItem('preferredZodiac', z);
                render(z);
                renderWeeklyStats(z);
            });

            el.complete.addEventListener('click', () => {
                const z = el.select.value;
                const content = dailyChallenge[z] || dailyChallenge.aries;
                localStorage.setItem(getStorageKey(z), '1');
                addToLogToday(z);
                render(z);
                renderWeeklyStats(z);
                openModal(content.feedback);
            });

            el.share.addEventListener('click', async () => {
                const z = el.select.value;
                const meta = zodiacMap[z];
                const text = `${meta.name} · ${getTodayKey()} · 我完成了今日小挑战！`;
                if (navigator.share) {
                    try { await navigator.share({ title: '星格每日小挑战', text, url: location.href }); } catch (e) {}
                } else {
                    navigator.clipboard && navigator.clipboard.writeText(text);
                    openModal('已复制到剪贴板，去分享你的今日成就吧！');
                }
            });

            el.modalClose.addEventListener('click', closeModal);
            el.modal.addEventListener('click', (e) => { if (e.target === el.modal) closeModal(); });
            const okBtn = document.getElementById('ok-feedback');
            const shareBtn = document.getElementById('share-feedback');
            if (okBtn) okBtn.addEventListener('click', closeModal);
            if (shareBtn) shareBtn.addEventListener('click', async () => {
                const z = el.select.value;
                const meta = zodiacMap[z];
                const text = `${meta.name} · ${getTodayKey()} · 我完成了今日小挑战！`;
                if (navigator.share) {
                    try { await navigator.share({ title: '星格每日小挑战', text, url: location.href }); } catch (e) {}
                } else {
                    navigator.clipboard && navigator.clipboard.writeText(text);
                }
            });
            // 预览按钮：打开完成反馈弹框
            const openPreview = document.getElementById('open-preview-modal');
            if (openPreview) openPreview.addEventListener('click', () => {
                const z = el.select.value;
                const content = dailyChallenge[z] || dailyChallenge.aries;
                openModal(content.feedback);
            });
            // 首次渲染周统计
            renderWeeklyStats(zodiac);
        })();
    </script>
</body>
</html>


